package com.yantong.service.impl;

import com.yantong.enums.MessageTypeEnum;
import com.yantong.pojo.*;
import com.yantong.mapper.CentreMapper;
import com.yantong.exception.BDException;
import com.yantong.utils.PageUtils;
import com.yantong.mapper.MessageMapper;
import com.yantong.mapper.MessageTypeMapper;
import com.yantong.service.MessageService;
import com.yantong.service.MemberService;
import com.yantong.utils.ValidateUtil;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageTypeMapper messageTypeMapper;
    @Autowired
    private MemberService memberService;
    @Autowired
    private CentreMapper centreMapper;

    /**
     * 列表
     */
    @Override
    public PageUtils<MessageType> messageTypeList(int offset, int limit) {
        Map<String, Object> params = new HashMap<String, Object>();
        PageUtils<MessageType> pageUtils = new PageUtils<>();
        int total = messageTypeMapper.countByParams(params);
        if (total > 0) {
            pageUtils.setTotal(total);
            pageUtils.setRows(messageTypeMapper.listByParams(params, new RowBounds(offset, limit)));
        }
        return pageUtils;
    }

    /**
     * 新增
     *
     * @param messageType
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addMessageType(MessageType messageType) {
        return messageTypeMapper.insertSelective(messageType);
    }

    /**
     * 删除
     *
     * @param type_id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteMessageType(Long type_id) {
        int errorNum=0;
        if (type_id == MessageTypeEnum.PUBLIC_NOTICE.getType()){
            errorNum=1;
        }
        else if (type_id == MessageTypeEnum.ORDER_NOTICE.getType()){
            errorNum=1;
        }
        else if (type_id == MessageTypeEnum.TEAM_NOTICE.getType()){
            errorNum=1;
        }
        else if (type_id == MessageTypeEnum.SYS_NOTICE.getType()){
            errorNum=1;
        }
        else if (type_id == MessageTypeEnum.PRIVATE_NOTICE.getType()){
            errorNum=1;
        }
        if (errorNum==1){
            throw new BDException("默认分类禁止更改和删除！");
        }
        else {return messageTypeMapper.deleteByPrimaryKey(type_id);}
    }

    /**
     * 后台消息
     *
     * @param offset
     * @param limit
     * @return
     */
    @Override
    public PageUtils<Message> backMessageList(int offset, int limit) {
        ListMessageParams params=new ListMessageParams();
        PageUtils<Message> pageUtils = new PageUtils<>();
        int total = messageMapper.countByParamsBack(params);
        if (total > 0) {
            pageUtils.setTotal(total);
            pageUtils.setRows(messageMapper.listByParamsBack(params, new RowBounds(offset, limit)));
        }
        return pageUtils;
    }

    /**
     * 限定范围后台消息
     *
     * @param offset
     * @param limit
     * @return
     */
    @Override
    public PageUtils<Message> backMessageListByCentreId(Long centreId,int offset, int limit){
        ListMessageParams params=new ListMessageParams();
        params.setCentreId(centreId);
        PageUtils<Message> pageUtils = new PageUtils<>();
        int total = messageMapper.countByParamsBack(params);
        if (total > 0) {
            pageUtils.setTotal(total);
            pageUtils.setRows(messageMapper.listByParamsBack(params, new RowBounds(offset, limit)));
        }
        return pageUtils;
    }

    /**
     * 后台新增
     *
     * @param message
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addMessageBack(Message message) {
        return messageMapper.addMessageBack(message);
    }

    /**
     * 后台获取消息
     *
     * @param id
     * @return
     */
    @Override
    public Message getMessageBackPrimaryKey(Long id) {
        return messageMapper.getMessageBackPrimaryKey(id);
    }

    /**
     * 后台修改消息
     *
     * @param message
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateMessageBack(Message message) {
        return messageMapper.updateMessageBack(message);
    }

    /**
     * 后台删除
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteMessageBack(Long id) {
        return messageMapper.deleteMessageBack(id);
    }

    /**
     * 获取消息类型
     *
     * @return
     */
    @Override
    public Map<String, Object> getMessageTypeListToMap() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<MessageType> list = messageTypeMapper.listByParams(map, new RowBounds());
        map.put("messageType", list);
        return map;
    }

    /**
     * 发送后台信息
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int sendMessageBack(Long id) {
        //获取这条信息的后台模板信息
        Message message = messageMapper.getMessageBackPrimaryKey(id);
        //获取需要发送的用户
        List<Member> members = memberService.listCenterList(message.getCentreId());
        //封装消息信息
        int insertnum=0;
        for (Member member : members) {
            Message mes = new Message();
            mes.setTypeId(message.getTypeId());
            mes.setMemberId(member.getId());
            mes.setContent(message.getContent());
            mes.setCentreId(message.getCentreId());
            mes.setTeamId(message.getTeamId());
            mes.setIsSend("1");
            messageMapper.insertSelective(mes);
            insertnum+=1;
        }
        //判断是否有插入数据操作
        if (insertnum<1) {
            return 0;
        }
        //修改后台模板数据的发送状态
        Message message_back = new Message();
        message_back.setId(id);
        message_back.setIsSend("1");
        if (messageMapper.updateMessageBack(message_back) < 1) {
            return 0;
        }
        return 1;
    }

    /**
     * 消息列表
     */
    @Override
    public PageUtils<Message> getMessageList(Long centreId,Long memberId,Long typeId,Long teamId,String isRead,int offset, int limit) {
        ListMessageParams listMessageParams = new ListMessageParams();
        listMessageParams.setMemberId(Long.valueOf(memberId));
        listMessageParams.setCentreId(Long.valueOf(centreId));
        if (ValidateUtil.isNotEmptyObjectOrString(typeId)) {
            listMessageParams.setTypeId(Long.valueOf(typeId));
        }
        if (ValidateUtil.isNotEmptyObjectOrString(teamId)) {
            listMessageParams.setTeamId(Long.valueOf(teamId));
        }
        if (ValidateUtil.isNotEmptyObjectOrString(isRead)){
            listMessageParams.setIsRead(isRead);
        }
        PageUtils<Message> pageUtils = new PageUtils<>();
        int total = messageMapper.countByParams(listMessageParams);
        if (total > 0) {
            pageUtils.setTotal(total);
            pageUtils.setRows(messageMapper.listByParams(listMessageParams, new RowBounds(offset, limit)));
        }
        return pageUtils;
    }

    /**
     * 一键已读
     */
    @Override
    public int messageListSetRead(Long centreId,Long memberId,Long typeId,Long teamId){
        ListMessageParams listMessageParams = new ListMessageParams();
        listMessageParams.setMemberId(Long.valueOf(memberId));
        listMessageParams.setCentreId(Long.valueOf(centreId));
        if (ValidateUtil.isNotEmptyObjectOrString(typeId)) {
            listMessageParams.setTypeId(Long.valueOf(typeId));
        }
        if (ValidateUtil.isNotEmptyObjectOrString(teamId)) {
            listMessageParams.setTeamId(Long.valueOf(teamId));
        }
        listMessageParams.setIsRead("0");

        int total = messageMapper.countByParams(listMessageParams);
        List<Message> messageList = messageMapper.listByParams(listMessageParams);
        int num=0;
        for (Message message:messageList) {
            message.setIsRead("1");
            messageMapper.updateByPrimaryKeySelective(message);
            num+=1;
        }
        return num;
    }


    /**
     * 设置已读
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int messageSetRead(Long id) {
        Message message=messageMapper.selectByPrimaryKey(id);
        if (ValidateUtil.isNotEmptyObjectOrString(message.getIsRead())){
            message.setIsRead("1");
            return messageMapper.updateByPrimaryKey(message);
        }
        else {
            return 0;
        }
    }




    /**
     * 获取消息
     *
     * @param id
     * @return
     */
    @Override
    public Message getMessageByKey(Long id) {
        Message message=messageMapper.selectByPrimaryKey(id);
        MessageType messageType=messageTypeMapper.selectByPrimaryKey(message.getTypeId());
        message.setTypeName(messageType.getTypeName());
        return message;
    }

    /**
     * 修改消息
     *
     * @param message
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateMessage(Message message) {
        return messageMapper.updateByPrimaryKeySelective(message);
    }

    /**
     * 前台新增
     *
     * @param message
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addMessage(Message message) {
        if (ValidateUtil.isEmptyObjectOrString(message.getTypeId())){
            if(ValidateUtil.isEmptyObjectOrString(message.getTeamId())){
                message.setTypeId(MessageTypeEnum.SYS_NOTICE.getType());
            }
            else {
                message.setTypeId(MessageTypeEnum.TEAM_NOTICE.getType());
            }
        }
        return messageMapper.insertSelective(message);
    }

    /**
     * 前台删除
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteMessage(Long id) {
        Message message=messageMapper.selectByPrimaryKey(id);
        if (ValidateUtil.isNotEmptyObjectOrString(message.getIsRead())){
            if (message.getIsRead().equals("1")){
                return 0;
            }
        }
        return messageMapper.deleteByPrimaryKey(id);
    }



//    /**
//     * 获取消息类型
//     *
//     * @return
//     */
//    @Override
//    public Map<String, Object> getDivisionListToMap() {
//        Map<String, Object> map = new HashMap<String, Object>();
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("isDivision", "1");
//        List<SysUser> list = userMapper.getListByParams(params, new RowBounds());
//        map.put("users", list);
//        return map;
//    }

    @Override
    public Map<String, Object> getCentreIdListToMap(){
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("status", "1");
        //List<SysUser> list = userMapper.getListByParams(params, new RowBounds());
        List<Centre> list = centreMapper.selectByMap(params, new RowBounds());
        map.put("centre", list);
        return map;
    }

    @Override
    public Map<String,Object> getCentreById(Long centreId){
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("centreId", centreId);
        params.put("status", "1");
        List<Centre> list = centreMapper.selectByMap(params, new RowBounds());
        map.put("centre", list);
        return map;
    }
}